import { pathToBase64, base64ToPath } from './image-tool.js';
import store from "./store.js";
let request = function (url, data = {}, method = "GET", showLoading = true, contentType = 'application/json') {
	if (showLoading) {
		uni.showLoading({
			title: "请求中"
		})
	}
	const userId = store.state.userInfo != undefined ? store.state.userInfo.userId : ''

	const token = uni.getStorageSync("token") != '' ? uni.getStorageSync("token") : ''
	return new Promise(function (resolve, reject) {
		uni.request({
			url: url,
			data: data,
			dataType: "json",
			method: method,
			header: {
				'content-type': contentType,
				// 'uid': userId,
				'token': token
			},
			success: (res) => {

				if(res.data.code=="40100"){
					uni.showLoading({
						title: "登录超时"
					})
					uni.clearStorageSync();
					uni.reLaunch({
						url: "/pages/login/login"
					})
				}
				resolve(res.data);
			},
			fail: (res) => {
				reject(res)
			},
			complete: (res) => {
				if (showLoading) {
					uni.hideLoading()
				}
			}
		})
	})
}

// 获取指定长度的随机字符串
let radomString = function (length) {
	var data = ["0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K",
		"L", "M", "N", "O", "P", "Q", "R", "S", "T", "U", "V", "W", "X", "Y", "Z", "a", "b", "c", "d", "e", "f", "g", "h",
		"i", "j", "k", "l", "m", "n", "o", "p", "q", "r", "s", "t", "u", "v", "w", "x", "y", "z"
	];
	var result = "";
	for (var i = 0; i < length; i++) {
		var r = Math.floor(Math.random() * 62); //取得0-62间的随机数，目的是以此当下标取数组data里的值！
		result += data[r]; //输出20次随机数的同时，让rrr加20次，就是20位的随机字符串了。
	}
	return result;
}

const formatTime = date => {
	var date = new Date(date)
	const year = date.getFullYear()
	const month = date.getMonth() + 1
	const day = date.getDate()
	const hour = date.getHours()
	const minute = date.getMinutes()
	const second = date.getSeconds()

	return [year, month, day].map(formatNumber).join('-') + ' ' + [hour, minute, second].map(formatNumber).join(':')
}

const formatNumber = n => {
	n = n.toString()
	return n[1] ? n : '0' + n
}

function encodeUtf8(text) {
	const code = encodeURIComponent(text);
	const bytes = [];
	for (var i = 0; i < code.length; i++) {
		const c = code.charAt(i);
		if (c === '%') {
			const hex = code.charAt(i + 1) + code.charAt(i + 2);
			const hexVal = parseInt(hex, 16);
			bytes.push(hexVal);
			i += 2;
		} else bytes.push(c.charCodeAt(0));
	}
	return bytes;
}


export default {
	request: request,
	radomString: radomString,
	formatTime: formatTime,
	encodeUtf8: encodeUtf8,
	pathToBase64,
	base64ToPath,
};
